package com.ufox.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.Verification;

import java.util.Date;
import java.util.Map;


public class JWTUtil {

    private static final String SECRET = "w!erf^&gdAd#rf$G^H^yfnS";

    /**
     * 获取token
     * @param map
     * @return
     *
     * header
     *
     * payload
     *
     * 签名
     */
    public static String getJWT(Map<String,Object> map){
       // HashMap<String, Object> JWTMap = new HashMap<>();
        //JWTMap.put("typ","JWT");
        //JWTMap.put("alg","HS256");

        long curTime = System.currentTimeMillis();

        JWTCreator.Builder builder = JWT.create().withHeader(map)
                .withIssuer("123")
                .withIssuedAt(new Date()).withExpiresAt(new Date(curTime+1000*3600));

        map.forEach((a,v)->{
            builder.withClaim(a,v+"");
        });

        String token = builder.sign(Algorithm.HMAC256(SECRET));

        return token;
    }

    /**
     *  验证token
     * @param token
     * @return
     */
    public static DecodedJWT verify(String token){
        Verification require = JWT.require(Algorithm.HMAC256(SECRET));
        DecodedJWT verify = require.build().verify(token);
        return verify;
    }

}